package com.kin207.netty.listener.server;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.handle.IMessageHandle;
import com.kin207.netty.handle.IMessageHandleAdapter;
import com.kin207.netty.listener.ListenerConfig;
import com.kin207.netty.listener.ServerListener;
import com.kin207.netty.server.IServer;

public class MessageHandleRegisterServerListener implements ServerListener {
	final static Logger logger = LoggerFactory.getLogger(MessageHandleRegisterServerListener.class);
	
	protected List<IMessageHandle> messageHandles;
	
	public void initialize(ListenerConfig cfg) {
		logger.info("cfg:{}", cfg);
		
		if(cfg!=null){
			messageHandles = new ArrayList();
			String messageHandleStr = cfg.getParam("messageHandles");
			logger.info("load messageHandleStr:{}", messageHandleStr);
			if(messageHandleStr!=null && !"".equals(messageHandleStr)){
				String[] classArr = messageHandleStr.split(",");
				for(String className : classArr){
					try {
						logger.info("add messageHandles:{}", className);
						IMessageHandle messageHandle = (IMessageHandle)Class.forName(className.trim()).newInstance();
						messageHandles.add(messageHandle);
					} catch (Exception e) {
						throw new RuntimeException(e.getMessage(), e);
					}
					
				}
			}
		}
	}

	public void created(IServer server) {
		if(messageHandles!=null){
			IMessageHandleAdapter messageHandleAdapter = server.getMessageHandleAdapter();
			for(IMessageHandle item : messageHandles){
				logger.info("register message handle, name:{}, param class:{}, handle class:{}", item.name(), item.paramClass(), item.getClass().getName());
				messageHandleAdapter.registerMessageHandle(item);
			}
		}
	}

	public void destroyed(IServer server) {
		logger.info("destroyed");
		if(messageHandles!=null){
			IMessageHandleAdapter messageHandleAdapter = server.getMessageHandleAdapter();
			for(IMessageHandle item : messageHandles){
				logger.info("remove message handle, name:{}, param class:{}, handle class:{}", item.name(), item.paramClass(), item.getClass().getName());
				messageHandleAdapter.removeMessageHandle(item.name());
			}
		}
	}

	public List<IMessageHandle> getMessageHandles() {
		return messageHandles;
	}

}
